<?php
/**
 * 用户下单
 */
namespace Home\Controller;


use Common\Library\Http\Request;
use Common\Library\Http\Response;
use Common\Library\SendSMS;
use Common\Vendor\Hook\BaseHook;
use Home\Model\ConsumeHistoryModel;
use Home\Model\CreditVettingModel;
use Home\Model\CustomerAuthModel;
use Home\Model\PositionModel;
use Home\Model\FinishModel;
use Think\Controller;
use Common\Library\BusinessException;
use Common\Library\Constant;
use Think\Log;
use Think\Rsa;
use Think\OpenapiClient;
use Think\OpenapiDevBase;
use Think\Cache\Driver\Redis;

class OrderController extends Controller
{
    public function __construct()
    {
        parent::__construct();

        try {
            //授权信用额度等级
            $this->_facilityOne = 20000;     //没有审核
            $this->_facilityTwo = 50000;     //已经审核
            $this->_facilityThree = 200000;  //审核中

            //是否自动审批
            $this->_approveAuto = false;

            Request::parse();
        } catch (BusinessException $e) {
            $this->ajaxReturn(['code' => $e->getCode(), 'msg' => $e->getMessage()]);
        }
    }

    /*************************************************************************
     * 功能描述：保存用户当前位置信息
     * 创建时间：2016-7-13
     *************************************************************************/
    private function saveLocationHistory()
    {
        $locationModel = D("CustomerLocationHistory");
        $locationData = [
            'customer_id' => I('post.customer_id', 0, 'intval'),
            'province' => I("post.province", ''),
            'city' => I("post.city", ''),
            'country' => I("post.country", ''),
            'address' => I("post.address", ''),
            'location' => I("post.location", ''),
            'add_time' => time()
        ];
        Log::write("Customer location:" . json_encode($locationData, JSON_UNESCAPED_UNICODE), Log::INFO);
        $locationModel->add($locationData);
    }
    /**********************容360|*复贷*******************************/
    
    /***********************容360|复贷*******************************/
    /***********************************************************/
    public function  rong_api(){
        //待加密参数串|rong_sign($data);
        $rsa= new Rsa();
        //$rsa->publicKey;公钥
        //$rsa->privateKey;私钥
        /*****************（融360）使用公钥加密|（找钱花）私钥解密**********************/
        $str = $rsa->publicEncrypt('hello', $rsa->publicKey);
        // 这里使用base64是为了不出现乱码，默认加密出来的值有乱码
        $str = base64_encode($str);
        $str = base64_decode($str);
        $privstr = $rsa->privateDecrypt($str, $rsa->privateKey);
        echo  $privstr;
        /*****************（融360）使用公钥加密|（找钱花）私钥解密**********************/
        /******************（找钱花）使用私钥加密|（融360）公钥解密*********************/
        $str = $rsa->privateEncrypt('world', $rsa->privateKey);
        // 这里使用base64是为了不出现乱码，默认加密出来的值有乱码
        $str = base64_encode($str);
        $str = base64_decode($str);
        $pubstr = $rsa->publicDecrypt($str, $rsa->publicKey);
        echo  $pubstr;
        /******************（找钱花）使用私钥加密|（融360）公钥解密*********************/




    }
    /***********************************************************/
    /************融360|openapi.rong360.com/gateway***********************/
    public function  rong_access(){
        $arr_=[];
        $arr_['biz_data']='245132241561415';



        $sample= new OpenapiClient();
        $sample->setMethod('is.api.v3.order.notifypushaddinfo');
        $sample->setField("version", "1.0");
        $sample->setField("biz_data",json_encode($arr_));
        $sample->setField("format", "json");
        $sample->setField("sign_type", "RSA");
        $ret= $sample->execute();
        echo '<pre>'; print_r($ret);

    }
    public  function  verify_rong(){
        $postArray = json_decode($strPost,true);
        $data =  $postArray['biz_data'];
        $sign = $postArray['sign'];
        log::rong_write('*******融360|推送报告|sign|'.$sign.'|************');
        $sample= new OpenapiDevBase();
        $orgPublicKey = '-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDwjs1tCSFINTS6KA4kIOjFyolF
LYMUedpHaih8ALzFXbcKtYt/O1b2AcriptgVY6vlCWowK7xGDwwcnlPJ1O4CRyP8
xMdhTqfdBHMgMM1yliRnNuggptoRF0bm1mtSD7ySHFaNq3X2mxzoFDZxOcPI6mBx
5GcjLntUQSbsAw16JwIDAQAB
-----END PUBLIC KEY-----';

        $ret = openssl_verify($data,base64_decode($sign),$orgPublicKey);
        log::rong_write('*******融360|推送报告|校验结果|'.$ret.'|************');
    }
    /************融360|openapi.rong360.com/gateway***********************/
    /*************************************************************************
     * 功能描述：下单的公共参数校验
     * 创建时间：2016-8-13
     *************************************************************************/
    public function orderCommonCheck($data, $checkPass = true)
    {
        Log::write("[".ACTION_NAME."][orderCommonCheck][customer_id=".$data['customer_id']."]:start", Log::INFO);
        $customerId = isset($data['customer_id']) ? $data['customer_id'] : 0;
        $merchantId = isset($data['merchant_id']) ? $data['merchant_id']: 0;
        $amount = isset($data['amount']) ? $data['amount'] : 0;
        $payPass = isset($data['pay_pass']) ? $data['pay_pass'] : '';
        $isInit = isset($data['is_init']) ? $data['is_init'] : 0;
        $downType = isset($data['down_type']) ? $data['down_type']: 0;
        if(!$customerId || !$merchantId || (!$amount && !$isInit) || !$downType){
            BusinessException::throwException(Constant::INVALID_PARAMETER);
        }

        //用户有效性校验
        $customer = M('Customer')->where(['id' =>$customerId])->find();
        if(!$customer){
            BusinessException::throwException(Constant::CUSTOMER_NOT_FOUND);
        }

        //商户有效性校验
        $Merchant = M('Merchant')->where(['id' => $merchantId,'status'=>'1'])->find();
        if(!$Merchant){
            BusinessException::throwException(Constant::MERCHANT_NOT_FOUND);
        }

        //支付密码正确性校验
        if($checkPass){
            /* 0. 密码参数校验 */
            if(!$payPass){
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }
            /* 1. 未设置密码提示 */
            if (!$customer['pay_pass']) {
                BusinessException::throwException(Constant::UNSET_PAY_PASS);
            }
            /* 2.密码不正确提示 */
            if (password_unmatched($payPass, $customer['pay_pass'])) {
                BusinessException::throwException(Constant::PAY_PASS_UNMATCHED);
            }
        }

        //校验用户当前是否为逾期未还款，是则不允许下单
        $chk = D('ConsumeHistory')->chkFineOrWaitReview($customerId);
        if($chk){
            BusinessException::throwException(Constant::ORDER_WAIT_OR_FINE);
        }

        //用户3个月内只允许下一单(已审核通过的，人工拒绝的，决策拒绝的)
        /*$has_order = M('ConsumeHistory')->where(['customer_id'=>$customerId,
            'status'=>['in','"'.ConsumeHistoryModel::STATUS_REVIEWED.','.ConsumeHistoryModel::STATUS_REVIEW_FAILED.','.
            ConsumeHistoryModel::STATUS_TONDDUN_FAILED.'"'], 'add_time'=>['GT', get_before_date(3)], 'type'=>['in', '1,2']])->select();
        if($has_order){
            foreach ($has_order as $v){
                //判断是否因为是本地人，如果是，则过滤掉
                $reason = M('DecisionEngineLog')->where(['consume_id'=>$v['id'], 'customer_id'=>$customerId])->find();
                if(!$reason){
                    BusinessException::throwException(Constant::ONCE_3MONTH);
                    break;
                }else{
                    if($reason['code'] != Constant::INVALID_LOCAL){
                        BusinessException::throwException(Constant::ONCE_3MONTH);
                        break;
                    }
                }
            }
        }*/

        $ret = ['customer' => $customer, 'merchant' => $Merchant];
        Log::write("[orderCommonCheck]:return=>".json_encode($ret, JSON_UNESCAPED_UNICODE), Log::INFO);
        Log::write("[".ACTION_NAME."][orderCommonCheck]:end\n", Log::INFO);

        return $ret;
    }

    /*************************************************************************
     * 功能描述：授信额度在200以内
     * 创建时间：2016-8-13
     *************************************************************************/
    private function facilityOne($amount, $customer)
    {
        Log::write("[".ACTION_NAME."][facilityOne][customer_id=".$customer['id']."]:start", Log::INFO);
        if($customer['amount'] == 0){
            $credit = D('CustomerAuth')->getCustomerAuth($customer['id']);
            if(!$credit){
                BusinessException::throwException(Constant::ID_NUM_NO_AUTHED);
            }
            if($credit['face_pass'] == 1){
                //未授信过的用户且活体检测，直接授信额度500
                $balanceAmount = $this->_facilityTwo;
            }else{
                //未授信过的用户且没有活体检测，直接授信额度200
                $balanceAmount = $this->_facilityOne;
            }
            $status = ConsumeHistoryModel::STATUS_WAITING_REPAY;
            $this->_approveAuto = true;
        }else{
            //已授信过的用户
            if($amount <= $customer['balance_amount']){
                /* 1.当前授信额度足够扣减 */
                $balanceAmount = 0;
                $status = ConsumeHistoryModel::STATUS_WAITING_REPAY;
            }else{
                switch ($customer['amount']){
                    /* 2.当前授信额度不够扣减，自动提升额度到500 */
                    case $customer['amount'] < $this->_facilityTwo:
                        $balanceAmount = $this->_facilityTwo - $this->_facilityOne;
                        $status = ConsumeHistoryModel::STATUS_WAITING_REPAY;
                        break;
                    /* 3.当前授信额度不够扣减，当前信用额度已经超过自动审批额度500，需要人工审批 */
                    case $customer['amount'] >= $this->_facilityTwo:
                        $balanceAmount = 0;
                        $status = ConsumeHistoryModel::STATUS_WAIT_REVIEWED;
                        break;
                }
            }
        }

        $data = ['balance_amount' => $balanceAmount, 'status' => $status];
        Log::write("[facilityOne]:return=>".json_encode($data,JSON_UNESCAPED_UNICODE), Log::INFO);
        Log::write("[".ACTION_NAME."][facilityOne]:end\n", Log::INFO);

        return $data;
    }

    /*************************************************************************
     * 功能描述：授信额度在500以内
     * 创建时间：2016-8-13
     *************************************************************************/
    private function facilityTwo($amount, $customer)
    {
        Log::write("[".ACTION_NAME."][facilityTwo][customer_id=".$customer['id']."]:start:\n
        【param1:".$amount."】【param2:".json_encode($customer)."】", Log::INFO);
        if($customer['amount'] == 0){
            //未授信过的用户，直接授信额度500
            $balanceAmount = $this->_facilityTwo;
            $this->_approveAuto = true;
            $status = ConsumeHistoryModel::STATUS_WAITING_REPAY;
        }else{
            //已授信过的用户
            if($amount <= $customer['balance_amount']){
                /* 1.当前授信额度足够扣减 */
                $balanceAmount = 0;
                $status = ConsumeHistoryModel::STATUS_WAITING_REPAY;
            }else{
                switch ($customer['amount']){
                    /* 2.当前授信额度不够扣减，自动提升额度到500 */
                    case $customer['amount'] < $this->_facilityTwo:
                        $balanceAmount = $this->_facilityTwo - $this->_facilityOne;
                        $status = ConsumeHistoryModel::STATUS_WAITING_REPAY;
                        break;
                    /* 3.当前授信额度不够扣减，当前信用额度已经超过自动审批额度500，需要人工审批 */
                    case $customer['amount'] >= $this->_facilityTwo:
                        $balanceAmount = 0;
                        $status = ConsumeHistoryModel::STATUS_WAIT_REVIEWED;
                        break;
                }
            }
        }

        $data = ['balance_amount' => $balanceAmount, 'status' => $status];
        Log::write("[facilityTwo]:return=>".json_encode($data,JSON_UNESCAPED_UNICODE), Log::INFO);
        Log::write("[".ACTION_NAME."][facilityTwo]:end\n", Log::INFO);

        return $data;
    }

    /*************************************************************************
     * 功能描述：授信额度在2000以内
     * 创建时间：2016-8-13
     *************************************************************************/
    private function facilityThree($amount, $customer, $data)
    {
        Log::write("[".ACTION_NAME."][facilityThree][customer_id=".$customer['id']."]:start", Log::INFO);
        if($amount <= $customer['balance_amount']){
            /* 1.当前授信额度足够扣减 */
            if($data['down_payment']){
                $status = ConsumeHistoryModel::STATUS_DOWN_PAYMENT;
            }else{
                $status = ConsumeHistoryModel::STATUS_WAITING_REPAY;
            }
        }else{
            /* 2.当前授信额度不够扣减，自动提升额度到500 */
            if($customer['amount'] <= $this->_facilityOne && $amount+($customer['amount'] - $customer['balance_amount']) <= $this->_facilityTwo) {
                $balanceAmount = $this->_facilityTwo;
                $status = ConsumeHistoryModel::STATUS_WAITING_REPAY;
            }else {
                /* 3.当前授信额度不够扣减，当前信用额度已经超过自动审批额度500，需要人工审批 */
                $balanceAmount = 0;
                $status = ConsumeHistoryModel::STATUS_WAIT_REVIEWED;
            }
        }

        $data = ['balance_amount' => 0, 'status' => $status];
        Log::write("[facilityThree]:return=>".json_encode($data,JSON_UNESCAPED_UNICODE), Log::INFO);
        Log::write("[".ACTION_NAME."][facilityThree]:end\n", Log::INFO);

        return $data;
    }

    /*************************************************************************
     * 功能描述：授信额度大于2000
     * 创建时间：2016-8-13
     *************************************************************************/
    private function facilityDefault($amount, $customer, $data)
    {
        Log::write("[".ACTION_NAME."][facilityDefault][customer_id=".$customer['id']."]:start", Log::INFO);
        if($amount <= $customer['balance_amount']){
            /* 1.当前授信额度足够扣减 */
            $status = ConsumeHistoryModel::STATUS_WAITING_REPAY;
        }else{
            $status = ConsumeHistoryModel::STATUS_WAIT_REVIEWED;
        }

        $data = ['balance_amount' => 0, 'status' => $status];
        Log::write("[facilityDefault]:return=>".json_encode($data,JSON_UNESCAPED_UNICODE), Log::INFO);
        Log::write("[".ACTION_NAME."][facilityDefault]:end\n", Log::INFO);

        return $data;
    }

    /*************************************************************************
     * 功能描述：分析是否自动审批及自动审批额度
     * 创建时间：2016-8-13
     *************************************************************************/
    private function approveAnalysis($amount, $customer, $data)
    {
        Log::write("[".ACTION_NAME."][approveAnalysis][customer_id=".$data['customer_id']."]:start", Log::INFO);
        switch ($amount+10){
            //消费金额小于200
            case $amount <= $this->_facilityOne+10;
                $ret = $this->facilityOne($amount, $customer); break;
            //消费金额小于500
            case $amount <= $this->_facilityTwo+10;
                $ret = $this->facilityTwo($amount, $customer); break;
            /************** 合并为一个分支，代码暂时保留 **************
            //消费金额小于2000
            case $amount <= $this->_facilityThree+10;
                $ret = $this->facilityThree($amount, $customer); break;
            //消费金额大于2000
            default:
                $ret = $this->facilityDefault($amount,$customer, $data);
             * ****************************************************** */
            //消费金额大于500
            default:
                $ret = $this->facilityThree($amount, $customer, $data);
        }
        Log::write("[approveAnalysis]:return=>".json_encode($ret,JSON_UNESCAPED_UNICODE), Log::INFO);
        Log::write("[".ACTION_NAME."][approveAnalysis]:end\n", Log::INFO);

        return $ret;
    }

    /*************************************************************************
     * 功能描述：记录消费历史列表信息
     * 创建时间：2016-8-14
     *************************************************************************/
    private function insConsumeHistory($money, $other)
    {
        Log::write("[".ACTION_NAME."][insConsumeHistory][customer_id=".$other['customer_id']."]:start", Log::INFO);
        $consumeData = [
            'amount' => $money['amount'],
            'consume_amount' => $money['consume_amount'],
            'discount_first_order' => $money['discount_first_order'],
            'discount_full_amount' => 0,
            'discount_full_reduce' => $money['discount_full_reduce'],
            'discount_rebate_amount' => $money['discount_rebate_amount'],
            'down_payment' => $money['down_payment'],
            'down_type' => $other['down_type'],
            'type' => $other['type'],
            'customer_id' => $other['customer_id'],
            'merchant_id' => $other['merchant_id'],
            'status' => $other['status'], //默认是未审核状态，最初始状态
            'repayment_time' => get_repayment_date(1),
            'repay_id' => $other['repay_id'],
            'county_id' => $other['county_id'],
            'add_time' => time()
        ];
        //分期大单入库
        if (!($insertId = D('ConsumeHistory')->add($consumeData))) {
            BusinessException::throwException(Constant::FAILED);
        }
        $mer = M("Merchant")->where("id=".$other['merchant_id'])->find();
        $commission_history = array(
            'history_id' => $insertId,
            'merchant_id' => $other['merchant_id'],
            'rebate_first' => $mer['rebate_first'],
            'rebate_last' => $mer['rebate_last'],
            'rebate_spare' => $mer['rebate_spare'],
            'addtime' =>time(),
            'sales_low'=>$mer['sales_low']       ///下单时的最低业绩
        );
         M("MerchantCommissionOrder")->add($commission_history);

        if(false === M('Customer')->execute("UPDATE `customer` SET `order_count`=`order_count` + 1  WHERE  `id` = '".$other['customer_id']."'")){
            BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
        }
        Log::write("[approveAnalysis]:return=>".$insertId, Log::INFO);
        Log::write("[".ACTION_NAME."][approveAnalysis]:end\n", Log::INFO);

        return $insertId;
    }

    /*************************************************************************
     * 功能描述：创建用户下单通用方法
     * 创建时间：2016-8-13
     *************************************************************************/
    public function createOrder($data, $type)
    {
        Log::write("[".ACTION_NAME."][createOrder][customer_id=".$data['customer_id']."]:start", Log::INFO);

        //公共参数的校验
        $res = $this->orderCommonCheck($data);
        //首付不为0
        $down_payment = $data['down_payment'];
        if($down_payment <= 0 ){
            BusinessException::throwException(Constant::INVALID_DOWN_PAY);
        }
        $repay_id = isset($data['repay_id']) ? $data['repay_id']: 0;
        $province = isset($data['province']) ? $data['province']: '';
        $city = isset($data['city']) ? $data['city']: '';
        $country = isset($data['country']) ? $data['country']: '';
        $location = isset($data['location']) ? $data['location']: '';
        $address = isset($data['address']) ? $data['address']: '';
        if(!$repay_id || !$province || !$city || !$country || !$location || !$address){
            BusinessException::throwException(Constant::INVALID_PARAMETER);
        }

        //计算优惠金额、商户金额、用户实付金额
        $res['customer']['consume_amount'] = $data['amount'];
        $money = D('Finish')->preFacilityForCommon($res['customer'], $res['merchant'], $data);

        //获取消费历史是否自动审批及自动审批额度
        $approve = $this->approveAnalysis($money['amount'], $res['customer'], $data);

        //检测用户是否购买过该商品，且需要审核，如果有则不可再次申请
        if($approve['status'] == ConsumeHistoryModel::STATUS_WAIT_REVIEWED){
            $wait = M("ConsumeHistory")->where(['customer_id' => $data['customer_id'],
                'merchant_id' => $data['merchant_id'], 'consume_amount' => $data['amount'],
                'status' => ['in', '"'.
                    ConsumeHistoryModel::STATUS_WAIT_REVIEWED.','.
                    ConsumeHistoryModel::STATUS_WAITING_REPAY.','.
                    ConsumeHistoryModel::STATUS_SEND_GOODS.','.
                    ConsumeHistoryModel::STATUS_SEND_MONEY_WAITING.','.
                    ConsumeHistoryModel::STATUS_SEND_MONEY_FAILED.','.
                    ConsumeHistoryModel::STATUS_REVIEW_CANCEL.','.
                    ConsumeHistoryModel::STATUS_WAIT_TWO.'"'
                ]])->find();
            if($wait){
                BusinessException::throwException(Constant::WAIT_FOR_REVIEW);
            }
        }
        
        if($money['amount'] <= Constant::DOWN_PAYMENT_START){
            BusinessException::throwException(Constant::ORDER_ERROR);
        }

        //地理位置&&保存位置信息
        $this->saveLocationHistory();

        //获取用户所在的区域id值
        $approve['county_id'] = D('Position')->getCountyIDByCountyName($province, $country);

        //录入消费列表数据(数据留痕，因此顺序调整到这里)
        $approve['customer_id'] = $data['customer_id'];
        $approve['merchant_id'] = $data['merchant_id'];
        $approve['type'] = $type;
        $approve['repay_id'] = $data['repay_id'];
        $approve['down_type'] = $data['down_type'];
        if(!($insertId = $this->insConsumeHistory($money, $approve))){
            BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
        }

        //信审额度计算
        if($approve['balance_amount']){
            $creditAmount = $approve['balance_amount'];
        }else if($money['amount'] - $res['customer']['amount'] > 0){
            $creditAmount = $money['amount'] - $res['customer']['amount'];
        }else{
            $creditAmount = 0;
        }
        if($approve['status'] == ConsumeHistoryModel::STATUS_WAIT_REVIEWED){
            $creditAmount = 0;
        }

        //记录信审表
        $creditVetting = [
            'customer_id' => $data['customer_id'],
            'consume_id' => $insertId,
            'credit_amount' => $creditAmount,
            'status' => $approve['status']==ConsumeHistoryModel::STATUS_WAIT_REVIEWED ? CreditVettingModel::STATUS_WAITING_REVIEW : 5,
            'type' => $type,
            'add_time'=> date('Y-m-d H:i:s', time())
        ];
        $ins = M('CreditVetting')->add($creditVetting);
        Log::write("[".ACTION_NAME."][记录信审信息][customer_id=".$data['customer_id']."]:".json_encode($creditVetting).",result:".$ins, Log::INFO);

        //首次激活额度or需要审批的订单需要调用执行决策
        $action = Constant::TONGDUN_NEXT;
        if($type == Constant::PAY_TYPE_INSTALLMENT){
            $action = Constant::TONGDUN_INST;
        }

        //同步最新的同盾设备id值
        $new_data_customer = [];
        $push_id = I('post.push_id', '', 'string');
        $tdId = I('post.black_box', '', 'string');
        if(!$tdId){
            BusinessException::throwException(Constant::INVALID_PARAMETER);
        }
        if(0 == strlen($res['customer']['tongdun_device_id']) || $tdId != $res['customer']['tongdun_device_id']){
            $new_data_customer['tongdun_device_id'] = $tdId;
        }
        if($push_id){
            $new_data_customer['push_id'] = $push_id;
        }
        if($new_data_customer){
            if(false === M('Customer')->where(['id' => $data['customer_id']])->setField($new_data_customer)){
                BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
            }
            $res['customer']['tongdun_device_id'] = $tdId;
        }
        $res['customer']['consume_id'] = $insertId;

        if($this->_approveAuto || $approve['status'] == ConsumeHistoryModel::STATUS_WAIT_REVIEWED){
            $ret = BaseHook::executeHook("DECISION_ENGINE_HOOK", $res['customer'], $action);
            Log::write("决策引擎:" . json_encode($ret), Log::INFO);
            if (Constant::SUCCESS != $ret['code']) {
                if($ret['code'] == Constant::INVALID_LOCAL){
                    $update['status'] = ConsumeHistoryModel::STATUS_REVIEW_FAILED;
                }else{
                    $update['status'] = ConsumeHistoryModel::STATUS_TONDDUN_FAILED;
                }
                if(false === D('ConsumeHistory')->where(['id' => $insertId])->setField($update)){
                    BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
                }
                $save_data = ['status'=>CreditVettingModel::STATUS_AUTO_REFUSE, 'reason'=>$ret['msg']];
                if(false === D('CreditVetting')->where(['id'=>$ins])->setField($save_data)){
                    BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
                }
                BusinessException::throwException($ret['code'], $ret['msg']);
            }
        }

        //组织返回值
        $res2App = Constant::getReturn(Constant::SUCCESS);
        $is_need_verify = ($approve['status'] == ConsumeHistoryModel::STATUS_WAIT_REVIEWED) ? 1 : 0;
        $is_need_fee = $money['down_payment']>0 ? 1 : 0;
        $res2App['down_payment'] = $money['down_payment'];
        $res2App['is_need_verify'] = $is_need_verify;
        $res2App['is_need_fee'] = $is_need_fee;
        if(!$is_need_verify && !$is_need_fee){
            //直接消费成功
            $order_res = $this->orderRealPay($insertId);
            $res2App = $res2App + $order_res;
        }else if($is_need_fee){
            $res2App['consume_id'] = $insertId;
            $bank = D('CustomerBankInfo')->getList($data['customer_id']);
            if(!$bank){
                $res2App['bind_card'] = 0; //未绑定银行卡
            }else{
                $res2App['bind_card'] = 1; //绑定银行卡
                $res2App['card_num'] = $bank[0]['card_num'];
                $res2App['bank_name'] = $bank[0]['card_user_name'];
            }
        }else{
            $res2App['consume_id'] = $insertId;
        }

        Log::write("[insCustomerBill]:return=>".json_encode($res2App, JSON_UNESCAPED_UNICODE), Log::INFO);
        Log::write("[".ACTION_NAME."][insCustomerBill]:end\n", Log::INFO);

        return $res2App;
    }
        /**********
         * 次月还款下单
         ********/
    public function orderNextMonthRepay()
    {
        try{
            $data = I('post.');
            Log::write("[start][orderNextMonthRepay][customer_id=".$data['customer_id']."]:开始执行", Log::INFO);
            $ret = Constant::getReturn(Constant::SUCCESS);
            $ret['data'] = $this->createOrder($data, Constant::PAY_TYPE_NEXT_MONTH);
            $repay_date = date('d',get_repayment_date(1));
            if($repay_date==31){
                $repay_date = '月底';
            }else{
                $repay_date =  $repay_date.'日';
            }
            $ret['data']['repay_date'] =$repay_date ;
        }catch (BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }

        Log::write("[end][orderNextMonthRepay][customer_id=".$data['customer_id']."]:执行结束", Log::INFO);

        Response::format($ret);
        $this->ajaxReturn($ret);
    }
    /*******
     * 分期付款下单
     *******/
    public function orderInstallmentRepay()
    {
        try{
            $data = I('post.');
            Log::write("[start][orderInstallmentRepay][customer_id=".$data['customer_id']."]:开始执行", Log::INFO);
            $ret = Constant::getReturn(Constant::SUCCESS);
            $ret['data'] = $this->createOrder($data, Constant::PAY_TYPE_INSTALLMENT);
            $repay_date = date('d',get_repayment_date(1));
            if($repay_date==31){
                $repay_date = '月底';
            }else{
                $repay_date =  $repay_date.'日';
            }
            $ret['data']['repay_date'] =$repay_date ;
        }catch (BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }

        Log::write("[end][orderInstallmentRepay][customer_id=".$data['customer_id']."]:执行结束", Log::INFO);

        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    /****** 真正的下单 ******/
    public function orderRealPay($consume_id = NULL){
        try{
            //参数校验
            $consume_id = $consume_id ? $consume_id : I('post.consume_id', 0, 'int');
            Log::write("[start][orderRealPay][consume_id=".$consume_id."]:开始执行", Log::INFO);
            if(!$consume_id){
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }
            
            D('Finish')->OrderFinish($consume_id);
            $ret = Constant::getReturn(Constant::SUCCESS);
        }catch (BusinessException $e){
            M('Finish')->rollback();
            $ret = ['code'=>$e->getCode(), 'msg'=>$e->getMessage()];
        }
        Log::write("[end][orderRealPay][consume_id=".json_encode($ret, JSON_UNESCAPED_UNICODE)."]:执行结束", Log::INFO);

        M('Finish')->commit();
        if(I('post.consume_id', 0, 'int')){
            Response::format($ret);
            $this->ajaxReturn($ret);
        }else{
            return $this->orderQuery($consume_id);
        }
    }

    /****** 预订单金额计算 ******/
    public function preOrderAmount(){
        try{
            $data = I('post.');
            //公共参数校验
            $res = $this->orderCommonCheck($data, false);

            if($data['is_init']){
                $money['installment_info'] = D('Finish')->getAllInstallmentDetail(0, $data['merchant_id']);
            }else{
                //计算金额
                $money = D('Finish')->preFacilityForCommon($res['customer'], $res['merchant'], $data);
                unset($money['merchant_gain_amount']);
                unset($money['consume_amount']);
                $money['type'] = $data['type'];
                if($data['type'] == Constant::PAY_TYPE_INSTALLMENT){
                    $money['installment_info'] = D('Finish')->getAllInstallmentDetail($money['amount'], $data['merchant_id']);
                }
            }
            $money['merchant_name'] = $res['merchant']['name'];
            $money['merchant_logo'] = $res['merchant']['logo'];

            $ret = Constant::getReturn(Constant::SUCCESS);
            $ret['img_url'] = C('ADMIN_SERVER_HOST');
            $ret['data'] = $money;
            Log::write("计算结果".json_encode($ret), Log::DEBUG);
        }catch (BusinessException $e){
            $ret = ['code'=>$e->getCode(), 'msg'=>$e->getMessage()];
        }
        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    /****** 待审核订单刷新 ******/
    public function orderRefresh(){
        try{
            $customerId = I('post.customer_id');
            $consumeId = I('post.consume_id');
            if(!$customerId || !$consumeId){
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }
            D('Customer')->has($customerId);
            //获取用户当前订单的状态
            $res = M('ConsumeHistory')->alias('h')
                ->join('left join merchant m on h.merchant_id = m.id')
                ->field('h.*, m.name as merchant_name')
                ->where(['h.id'=>$consumeId])->find();
            Log::write('data='.json_encode($res), Log::DEBUG);
            Log::write('sql='.M('ConsumeHistory')->getLastSql(), Log::DEBUG);
            $res['consume_id'] = $res['id'];
            $res['repay_type'] = $res['type'];
            $data = D('ConsumeHistory')->getCurOrderStatus($res);
            Log::write('data='.json_encode($data), Log::DEBUG);
            $order_step = [];

            $new_id = sprintf('%010s', $res['id']);
            $data['order_id'] = date('ymd', $res['add_time']) . $new_id;
            $data['merchant_name'] = $data['merchant_name'] ? $data['merchant_name'] : $res['merchant_name'];
            $data['add_time'] = $data['add_time'] ? $data['add_time'] : date('Y-m-d H:i:s', $res['add_time']);
            $data['amount'] = $data['amount'] ? $data['amount'] : $res['amount'];
            //业务员拒绝客户端进行虚拟成功展示
            Log::write($data['status'], Log::DEBUG);
            if(($data['status'] == ConsumeHistoryModel::STATUS_REVIEW_FAILED) && (time()) - $res['add_time'] < 5*60) {
                //第2步：贷前照片待上传（市场初审待审核）
                $where = [
                    'consume_id' => $res['id'],
                    'status' => ['in',
                        CreditVettingModel::STATUS_WAITING_REVIEW.",".
                        CreditVettingModel::STATUS_MARKET_REFUSE
                    ]
                ];
                //获取各步骤的时间 2
                $credit_data = M('CreditVetting')->where($where)->select();
                Log::write('jujue='.M('CreditVetting')->getLastSql(), Log::DEBUG);
                if(count($credit_data) >= 2){
                    $order_step = Constant::$step;
                    foreach ($order_step as $k => $v) {
                        $order_step[$k]['date_time'] = date('Y-m-d H:i:s', time());
                    }

                    $data['cur_step'] = 2;
                    $data['err_code'] = 2;
                    $data['status'] = ConsumeHistoryModel::STATUS_WAIT_REVIEWED;
                    $data['discount'] = $res['discount_interest'] == 2 ? 1 : 0;
                    $new_id = sprintf('%010s', $res['id']);
                    $data['order_id'] = date('ymd', $res['add_time']) . $new_id;

                    foreach ($credit_data as $k=>$value){
                        if ($value['status'] == CreditVettingModel::STATUS_WAITING_REVIEW){
                            $order_step[0]['date_time'] = $value['add_time'];
                        } elseif ($value['status'] == CreditVettingModel::STATUS_MARKET_REFUSE){
                            $order_step[1]['date_time'] = $value['add_time'];
                            $order_step[1]['display'] = '审核照片已由业务员代表辅助上传成功';
                        }
                    }
                    $data['step'] = $order_step;
                    $data['status'] = ConsumeHistoryModel::STATUS_WAIT_REVIEWED;
                }
            } elseif ($data['status'] == ConsumeHistoryModel::STATUS_WAIT_REVIEWED) {
                $order_step = Constant::$step;
                foreach ($order_step as $k => $v) {
                    $order_step[$k]['date_time'] = date('Y-m-d H:i:s', time());
                }

                $data['cur_step'] = 0;
                $data['err_code'] = 0;
                $data['discount'] = $res['discount_interest'] == 2 ? 1 : 0;

                //审批状态 1:信审部通过 2:待审核 3:信审部拒绝 4:决策拒绝 5:自动审核通过 6:市场部通过 7:市场部强烈通过 8:市场部拒绝 9:业务员担保 10:信审初审不合格 11:信审初审合格 12:信审复审不合格 13:市场复审通过
                if ($res['status'] == ConsumeHistoryModel::STATUS_WAIT_REVIEWED) {
                    //第2步：贷前照片待上传（市场初审待审核）
                    $data['cur_step'] = 1;
                    //获取各步骤的时间 2
                    $where = [
                        'consume_id' => $res['id'],
                        'status' => CreditVettingModel::STATUS_WAITING_REVIEW
                    ];
                    $credit_data = M('CreditVetting')->where($where)->find();
                    $order_step[0]['date_time'] = $credit_data['add_time'];
                } elseif ($res['status'] == ConsumeHistoryModel::STATUS_WAIT_TWO) {
                    //第3步：贷前照片待审核（信审初审待审核）
                    $data['cur_step'] = 2;
                    //获取各步骤的时间 2,6||7
                    $where = [
                        'consume_id' => $res['id'],
                        'status' => ['in',
                            CreditVettingModel::STATUS_WAITING_REVIEW.",".
                            CreditVettingModel::STATUS_MARKET_REVIEWED.",".
                            CreditVettingModel::STATUS_MARKET_REVIEWEDER
                        ]
                    ];
                    $credit_data = M('CreditVetting')->where($where)->select();
                    Log::write('sql='.M('CreditVetting')->getLastSql(), Log::DEBUG);
                    foreach ($credit_data as $k=>$value){
                        if ($value['status'] == CreditVettingModel::STATUS_WAITING_REVIEW){
                            $order_step[0]['date_time'] = $value['add_time'];
                        } elseif ($value['status'] == CreditVettingModel::STATUS_MARKET_REVIEWED || $value['status'] == CreditVettingModel::STATUS_MARKET_REVIEWEDER){
                            $order_step[1]['date_time'] = $value['add_time'];
                            $order_step[1]['display'] = '审核照片已由业务员代表辅助上传成功';
                        }
                    }
                } elseif ($res['status'] == ConsumeHistoryModel::STATUS_REVIEW_CANCEL) {
                    //第3步：贷前照片待审核（市场重新上传照片，信审初审待审核）
                    $data['cur_step'] = 2;
                    //获取各步骤的时间 2,6||7,10,14
                    $where = [
                        'consume_id' => $res['id'],
                        'status' => ['in',
                            CreditVettingModel::STATUS_WAITING_REVIEW.",".
                            CreditVettingModel::STATUS_MARKET_REVIEWED.",".
                            CreditVettingModel::STATUS_MARKET_REVIEWEDER.",".
                            CreditVettingModel::STATUS_MANUAL_FIRST_NOPASS.",".
                            CreditVettingModel::STATUS_MANUAL_CREDIT_ERR
                        ]
                    ];
                    $credit_data = M('CreditVetting')->where($where)->select();
                    foreach ($credit_data as $k=>$value){
                        if ($value['status'] == CreditVettingModel::STATUS_WAITING_REVIEW){
                            $order_step[0]['date_time'] = $value['add_time'];
                        } elseif ($value['status'] == CreditVettingModel::STATUS_MARKET_REVIEWED || $value['status'] == CreditVettingModel::STATUS_MARKET_REVIEWEDER){
                            $order_step[1]['date_time'] = $value['add_time'];
                            $order_step[1]['display'] = '审核照片已由业务员代表辅助上传成功';
                        } elseif ($value['status'] == CreditVettingModel::STATUS_MANUAL_FIRST_NOPASS){
                            $order_step[2]['date_time'] = $value['add_time'];
                            $order_step[2]['display'] = '图片资料不合格，请业务代表用小工具辅助重新提交';
                            $data['err_code'] = 3;
                        } elseif ($value['status'] == CreditVettingModel::STATUS_MANUAL_CREDIT_ERR){
                            $order_step[2]['date_time'] = $value['add_time'];
                            $order_step[2]['display'] = '运营商信息没有收到，请业务代表辅助用链接重新认证';
                            $data['err_code'] = 1;
                        }
                    }
                } elseif ($res['status'] == ConsumeHistoryModel::STATUS_SEND_GOODS) {
                    //第4步：发货照片待上传（市场复审待审核）
                    $data['cur_step'] = 3;
                    //获取各步骤的时间 2,6||7,11
                    $where = [
                        'consume_id' => $res['id'],
                        'status' => ['in',
                            CreditVettingModel::STATUS_WAITING_REVIEW.",".
                            CreditVettingModel::STATUS_MARKET_REVIEWED.",".
                            CreditVettingModel::STATUS_MARKET_REVIEWEDER.",".
                            CreditVettingModel::STATUS_MANUAL_FIRST_PASS
                        ]
                    ];
                    $credit_data = M('CreditVetting')->where($where)->select();
                    foreach ($credit_data as $k=>$value){
                        if ($value['status'] == CreditVettingModel::STATUS_WAITING_REVIEW){
                            $order_step[0]['date_time'] = $value['add_time'];
                        } elseif ($value['status'] == CreditVettingModel::STATUS_MARKET_REVIEWED || $value['status'] == CreditVettingModel::STATUS_MARKET_REVIEWEDER){
                            $order_step[1]['date_time'] = $value['add_time'];
                            $order_step[1]['display'] = '审核照片已由业务员代表辅助上传成功';
                        } elseif ($value['status'] == CreditVettingModel::STATUS_MANUAL_FIRST_PASS){
                            $order_step[2]['date_time'] = $value['add_time'];
                            $order_step[2]['display'] = '您的申请信审审核已通过';
                        }
                    }
                } elseif ($res['status'] == ConsumeHistoryModel::STATUS_SEND_MONEY_WAITING) {
                    //第5步：等待放款（信审复审待审核）
                    $data['cur_step'] = 4;
                    //获取各步骤的时间 2,6||7,11,13
                    $where = [
                        'consume_id' => $res['id'],
                        'status' => ['in',
                            CreditVettingModel::STATUS_WAITING_REVIEW.",".
                            CreditVettingModel::STATUS_MARKET_REVIEWED.",".
                            CreditVettingModel::STATUS_MARKET_REVIEWEDER.",".
                            CreditVettingModel::STATUS_MANUAL_FIRST_PASS.",".
                            CreditVettingModel::STATUS_MARKET_NEXT_PASS
                        ]
                    ];
                    $credit_data = M('CreditVetting')->where($where)->select();
                    foreach ($credit_data as $k=>$value){
                        if ($value['status'] == CreditVettingModel::STATUS_WAITING_REVIEW){
                            $order_step[0]['date_time'] = $value['add_time'];
                        } elseif ($value['status'] == CreditVettingModel::STATUS_MARKET_REVIEWED || $value['status'] == CreditVettingModel::STATUS_MARKET_REVIEWEDER){
                            $order_step[1]['date_time'] = $value['add_time'];
                            $order_step[1]['display'] = '审核照片已由业务员代表辅助上传成功';
                        } elseif ($value['status'] == CreditVettingModel::STATUS_MANUAL_FIRST_PASS){
                            $order_step[2]['date_time'] = $value['add_time'];
                            $order_step[2]['display'] = '您的申请信审审核已通过';
                        } elseif ($value['status'] == CreditVettingModel::STATUS_MARKET_NEXT_PASS){
                            $order_step[3]['date_time'] = $value['add_time'];
                            $order_step[3]['display'] = '您的提货单已上传成功';
                        }
                    }
                } elseif ($res['status'] == ConsumeHistoryModel::STATUS_SEND_MONEY_FAILED) {
                    //第5步：等待放款（市场重新上传照片，信审复审待审核）
                    $data['cur_step'] = 4;
                    //获取各步骤的时间 2,6||7,11,12
                    $where = [
                        'consume_id' => $res['id'],
                        'status' => ['in',
                            CreditVettingModel::STATUS_WAITING_REVIEW.",".
                            CreditVettingModel::STATUS_MARKET_REVIEWED.",".
                            CreditVettingModel::STATUS_MARKET_REVIEWEDER.",".
                            CreditVettingModel::STATUS_MANUAL_FIRST_PASS.",".
                            CreditVettingModel::STATUS_MANUAL_NEXT_NOPASS
                        ]
                    ];
                    $credit_data = M('CreditVetting')->where($where)->select();
                    foreach ($credit_data as $k=>$value){
                        if ($value['status'] == CreditVettingModel::STATUS_WAITING_REVIEW){
                            $order_step[0]['date_time'] = $value['add_time'];
                        } elseif ($value['status'] == CreditVettingModel::STATUS_MARKET_REVIEWED || $value['status'] == CreditVettingModel::STATUS_MARKET_REVIEWEDER){
                            $order_step[1]['date_time'] = $value['add_time'];
                            $order_step[1]['display'] = '审核照片已由业务员代表辅助上传成功';
                        } elseif ($value['status'] == CreditVettingModel::STATUS_MANUAL_FIRST_PASS){
                            $order_step[2]['date_time'] = $value['add_time'];
                            $order_step[2]['display'] = '您的申请信审审核已通过';
                        } elseif ($value['status'] == CreditVettingModel::STATUS_MARKET_NEXT_PASS){
                            $order_step[3]['date_time'] = $value['add_time'];
                            $order_step[3]['display'] = '您的提货单已上传成功';
                        } elseif ($value['status'] == CreditVettingModel::STATUS_MANUAL_NEXT_NOPASS){
                            $order_step[4]['date_time'] = $value['add_time'];
                            $order_step[4]['display'] = '提货单上传信息有误，请改正后重新上传';
                            $data['err_code'] = 3;
                        }
                    }
                } else {
                    BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
                }
                $data['step'] = $order_step;
            }

            $ret = Constant::getReturn(Constant::SUCCESS);
            $ret['data'] = $data;
        }catch (BusinessException $e){
            $ret = ['code'=>$e->getCode(), 'msg'=>$e->getMessage()];
        }
        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    /****** 取消订单 ******/
    public function orderCancel(){
        try{
            $customerId = I('post.customer_id');
            $consumeId = I('post.consume_id');
            if(!$customerId || !$consumeId){
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }
            D('Customer')->has($customerId);
            $res = M('ConsumeHistory')->where(['id' => $consumeId])->find();
            if(!$res){
                BusinessException::throwException(Constant::ORDER_ID_NOT_FOUNT);
            }
            if($res['status'] != ConsumeHistoryModel::STATUS_DOWN_PAYMENT && $res['status'] != ConsumeHistoryModel::STATUS_WAITING_REPAY){
                BusinessException::throwException(Constant::ORDER_ID_STATUS_ERROR);
            }
            //获取用户当前订单的状态
            if(false === M('ConsumeHistory')->where(['id' => $consumeId])->setField('status', ConsumeHistoryModel::STATUS_CANCEL)){
                BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
            }

            $ret = Constant::getReturn(Constant::SUCCESS);
        }catch (BusinessException $e){
            $ret = ['code'=>$e->getCode(), 'msg'=>$e->getMessage()];
        }
        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    /*** 下单查询 ***/
    public function orderQuery($consume_id = NULL)
    {
        try{
            $consume_id = $consume_id ? $consume_id : I('post.consume_id', 0, 'int');
            if(!$consume_id){
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }

            $cur_order = M('ConsumeHistory')->where(['id'=>$consume_id])->find();
            if($cur_order['status'] == ConsumeHistoryModel::STATUS_REVIEW_FAILED){
                $ret = ['code'=>'-1', 'msg'=>'亲，很抱歉，您的订单没有通过审核'];
            }else if($cur_order['status'] == ConsumeHistoryModel::STATUS_TONDDUN_FAILED){
                $credit = M('CreditVetting')->where(['id'=>$consume_id, 'status'=>CreditVettingModel::STATUS_AUTO_REFUSE])->find();
                $ret = ['code'=>'-2', 'msg'=>$credit['reason']];
            }else if($cur_order['status'] == ConsumeHistoryModel::STATUS_CANCEL){
                $ret = ['code'=>'-3', 'msg'=>'亲，您已经取消了该订单'];
            }else if($cur_order['status'] == ConsumeHistoryModel::STATUS_REVIEWED){
                $newCustomer = M('customer')->where(['id' => $cur_order['customer_id']])->field('amount, balance_amount')->find();
                $res2App = [
                    'amount' => $cur_order['consume_amount'],
                    'repay_type' => $cur_order['type'],
                    //'repay_date' => Constant::BILL_LAST_DAY,
                    'repay_date' => date('d',$cur_order['repayment_time']).'日',
                    'repay_total' => $cur_order['amount'],
                    'credit' => $newCustomer['amount'],
                    'balance_amount' => $newCustomer['balance_amount'],
                    'max_amount' => Constant::MAX_CREDIT_AMOUNT,
                    'discount' => $cur_order['discount_first_order'] + $cur_order['discount_full_reduce'] + $cur_order['discount_rebate_amount'],
                    'real_pay' => $cur_order['amount'],
                    'down_payment' => $cur_order['down_payment']
                ];

                if($cur_order['type'] == Constant::PAY_TYPE_INSTALLMENT){
                    //计算分期本金和利息,单位分
                    $config = D('Finish')->getInterestStandardConf($cur_order['merchant_id'], $cur_order['repay_id']);
                    if($cur_order['discount_interest'] == FinishModel::SYSTEM_DISCOUNT && $config['discount_interest']){
                        $config['interest_rate'] = $config['discount_interest'];
                        $config['interest_type'] = FinishModel::SYSTEM_DISCOUNT;
                    }
                    $res = D('Finish')->getInstallmentDetail($cur_order['amount'], $config);
                    $res2App['repay_times'] = $config['repay_times'];
                    $res2App['repay_principal'] = $res['principal'];
                    $res2App['repay_interest'] = $res['interest'];
                    $res2App['repay_total'] = $res['bill'];
                }
                $ret = Constant::getReturn(Constant::SUCCESS);
                $ret['data'] = $res2App;
                $ret['data']['state'] = 1;
            }else{
                $ret['data']['state'] = 2;
            }
        }catch (BusinessException $e){
            $ret = ['code'=>$e->getCode(), 'msg'=>$e->getMessage()];
        }
        if(I('post.consume_id', 0, 'int')){
            Response::format($ret);
            $this->ajaxReturn($ret);
        }else{
            return $ret['data'];
        }
    }
    
     /**
     * [customerFewMsg 新老用户是否超过三十天或逾期需要重新认证]
     * @return [type] [description]
     */
    public function customerFewMsg()
    {
        $customer_id = I('post.customer_id');
        Log::rong_write("*********|customerFewMsg|Request|customer_id|" .$customer_id. "*************************");
        try {
            $customer = D('customer')->has($customer_id);
            $ConsumeHistoryInfo = M('ConsumeHistory')->where("customer_id = '$customer_id' and type = 4")->order('add_time desc')->find();
            // var_dump($ConsumeHistoryInfo);die;
            if ($ConsumeHistoryInfo) {
                $is_new = 0;//不是新用户
            } else {
                $is_new = 1;//是新用户
            }

            $is_need_verify = 0;//初始化默认不需要重新认证
            $whereis = [
                'mobile'=>$customer['mobile']
            ];

            $redis = new Redis();
                //查询是用户最后一条的记录->field('add_time')
                $certificateDataInfo = D('CertificateData')->where($whereis)->order('add_time desc')->find();
                // var_dump($certificateDataInfo);die;
                $china = D('CustomerAuth')->field('china_mobile')->where(['customer_id'=>$customer_id])->find();
                //判断用户上次认证时间
                $now = time();
                // var_dump($certificateDataInfo['add_time']);die;
                @$diffTime = ($now - $certificateDataInfo['add_time']);
                Log::rong_write("*********|customerFewMsg|判断用户上次认证时间|diffTime" .$diffTime. "*************************");
                //老用户运营商认证是否大于30天的 和 新用户未认证则必须认证
                if ($diffTime > 30 * 24 * 3600 && $china['china_mobile'] == 1){
                    $scredit = D('CustomerAuth')->saveCustomerAuth($customer_id);//修改运营商认证状态 china_mobile=0
                    Log::rong_write("大于30天且china_mobile=1*********is_need_verify=1|customerFewMsg|saveCustomerAuth修改运营商认证状态结果|" .$scredit. "*************************");
                    // if (!$scredit){
                    //     BusinessException::throwException(Constant::INVALID_PARAMETER);
                    // }
                    $czhima = D('Customer')->saveCustomerzhima($customer_id);//更新芝麻分认证状态 sesame_score=0
                    Log::rong_write("大于30天且china_mobile=1*********is_need_verify=1|customerFewMsg|saveCustomerzhima更新芝麻分认证状态结果|" .$czhima. "*************************");
                    // if (!$czhima){
                    //     BusinessException::throwException(Constant::INVALID_PARAMETER);
                    // }
                    // $key = '该用户需要重新认证-'.$customer_id;
                    // $redis_res = $redis->set($key,'10');
                    $key = '该用户需要重新认证-'.$customer_id;
                    $redis_res = $redis->set($key,'10');
                    Log::rong_write('大于30天且china_mobile=1**********is_need_verify=1|再次拉取客户身份认证：'.$customer_id.'|存入Redis中|'.$redis_res);

                    $is_need_verify = 1;
                    // Log::write('**********|再次拉取客户身份认证：'.$customer_id.'|存入Redis中|'.$redis_res);
                } elseif ($china['china_mobile'] == 0) {
                    $czhima = D('Customer')->saveCustomerzhima($customer_id);//更新芝麻分认证状态 sesame_score=0
                    Log::rong_write("china_mobile=0*********is_need_verify=1|customerFewMsg|saveCustomerzhima只更新芝麻分认证状态结果|" .$czhima. "*************************");
                    //此处新用户还未进行运营商认证，所以也需要认证,但不需要弹窗
                    // $key = '该用户需要重新认证-'.$customer_id;
                    // $redis_res = $redis->set($key,'10');
                    // Log::write('**********|再次拉取客户身份认证：'.$customer_id.'|存入Redis中|'.$redis_res);

                    $is_need_verify = 1;
                }



                //查询用户订单信息
                $fconsume = M('ConsumeHistory')->where(['customer_id'=>$customer_id,'status'=>3])->order('add_time desc')->find();
                $paylog = M('CustomerBillPayLog')->where(['consume_id'=>$fconsume['id']])->order("pay_time desc")->find();
                $consumehistory = M('ConsumeInstallmentHistory')->where(['parent_id'=>$fconsume['id']])->find();
                $key1 = '该用户需要重新认证-'.$customer_id;
                if (($paylog['amount'] != $consumehistory['amount']) || $redis->get($key1)){
                    $key2 = '该用户弹窗时间'.$customer_id;
                    if (!$redis->get($key2)){
                        $key2 = '该用户弹窗时间'.$customer_id;
                        $redis->set($key2,'11');
                        $test = 1;
                    } else {
                        $test = 0;
                    }
                } else {
                    $test = 0;
                }
                $tel_re = $test?$test:0;

                //运营商认证大于30天 和 最近一次是否逾期过的判断
                $cust = M('Customer')->where(['id'=>$customer_id])->find();
                if ($cust['accreditation_status'] == 1 || $is_need_verify){
                    // Log::rong_write("*******customerFewMsg|".$customer_id."需要重新认证|*******：");
                    // if($cust['accreditation_status'] ==1){
                    //     $data1 = [
                    //         'accreditation'=>0
                    //     ] ;
                    //     Log::rong_write("*******customerFewMsg|".$customer_id."accreditation|字段清零*******：");
                    //     M('Customer')->where(['id'=>$customer_id])->save($data1);
                    // }
                    //需要重新拉取通讯录等信息
                    $is_need_verify = 1;
                    Log::rong_write("*******customerFewMsg|".$customer_id."accreditation_status". $cust['accreditation_status'] ."|is_need_verify字段为1*******：");
                } else {
                    Log::rong_write("*******customerFewMsg|".$customer_id."accreditation_status". $cust['accreditation_status'] ."|is_need_verify字段为0*******：");
                    $is_need_verify = 0;
                }
                //查询用户订单信息
                /*$fconsume = M('ConsumeHistory')->where(['customer_id'=>$customer_id,'status'=>3])->order('add_time desc')->limit(1)->find();
                $paylog = M('CustomerBillPayLog')->where(['consume_id'=>$fconsume['id']])->find();
                $consumehistory = M('ConsumeInstallmentHistory')->where(['parent_id'=>$fconsume['id']])->find();
                if (($paylog['amount'] != $consumehistory['amount']) || $redis->get($key)){
                    //需要重新拉取通讯录等信息
                    $res2App['tel_refresh'] = 1;
                } else {
                    $res2App['tel_refresh'] = 0;
                }*/
                $xml_data = [
                    'is_new'    =>  $is_new,
                    'is_need_verify'   =>  $is_need_verify,
                    'tel_re'    =>  $tel_re
                ];
                Log::rong_write('*********|xml_data|'. json_encode($xml_data) .'|**********');
                $ret = Constant::getReturn(Constant::SUCCESS);
                $ret['data'] = $xml_data;
        } catch (BusinessException $e) {
            Log::rong_write('*********|异常抛出|code'. $e->getCode() .'|msg'. $e->getMessage() .'|**********');
            $ret = ['code'=>$e->getCode(), 'msg'=>$e->getMessage()];
        }
        $this->ajaxReturn($ret);
    }
    /**
     * [orderReset 解决提现失败接口]
     * @return [json] [code,msg]
     */
    public function orderReset()
    {
        log::rong_write('***************************|orderReset_Start|****************************');
        $customer_id = I("post.customer_id");
        $customer_id ? : BusinessException::throwException(Constant::INVALID_PARAMETER);
        // var_dump($customer_id);
        $consume_id = I("post.consume_id");
        $consume_id ? : BusinessException::throwException(Constant::INVALID_PARAMETER);
        log::rong_write('*********|接收数据|customer_id'. $customer_id .'|consume_id'. $consume_id .'|**********');

        try {
            $CustomerInfo = D('Customer')->has($customer_id);//customer_id数据库校验

            $ConsumeHistoryInfo = M('ConsumeHistory')->field("id")->where("customer_id = '$customer_id' and type = 5 and status <> 3")->order("add_time desc")->find();//
            $consume_id_ = $ConsumeHistoryInfo['id'];
            // var_dump($consume_id,$consume_id_);die;
            Log::rong_write('*********|$ConsumeHistoryInfo[id]|consume_id'. $consume_id .'|consume_id_'. $consume_id_ .'|**********');

            if ($consume_id == $consume_id_) {
            //这里先验证一下post上来的订单是不是跟ConsumeHistory表里最新的type=5的订单号相同。
            //若相同则进行下一步pay_log表验证数据是否相同
         //       $CustomerPayLogInfo = M('customer_pay_log')->field("consume_id, pay_time, ret_msg")->where("customer_id = '$customer_id'")->order("create_time desc")->find();
           //     $consume_id_ = $CustomerPayLogInfo['consume_id'];
             //   $pay_time = $CustomerPayLogInfo['pay_time'];
               // $ret_msg = $CustomerPayLogInfo['ret_msg'];
               // Log::rong_write('*********|$CustomerPayLogInfo[id]|consume_id'. $consume_id .'|consume_id_'. $consume_id_ .'|**********');
               // Log::rong_write('*********|$CustomerPayLogInfo|consume_id_'. $consume_id_ .'|pay_time'. $pay_time .'|ret_msg'. $ret_msg .'**********');

               // if ($consume_id == $consume_id_ && $pay_time == 0 && $ret_msg !== 'success') {

                    if ($CustomerInfo['cash_amount'] > $CustomerInfo['balance_cash_amount']) {
                        $res = M('Customer')->where("id = '$customer_id'")->setField(array(
                            'balance_cash_amount'   =>  $CustomerInfo['cash_amount'],
                            'balance_prepaid'       =>  '0'
                            ));
                        log::rong_write('**********|cash_amount>balance_cash_amount|res_Customer_setField|'. $res .'|**********');
                    } else {
                        $res = M('Customer')->where("id = '$customer_id'")->setField(array(
                            'balance_prepaid'       =>  '0'
                            ));
                        //这里提现失败的话逻辑上应该就是0，确保无误所以这里再设置一下
                        log::rong_write('**********|cash_amount<=balance_cash_amount|res_Customer_setField|'. $res .'|**********');
                    }

                    $res = M('ConsumeHistory')->where("id = '$consume_id' and type = 5 and status <> 3")->delete();
                    log::rong_write('**********|res_ConsumeHistory_delete|'. $res .'|**********');


                    if (isset($res) && !empty($res)) {
                        
                        {
                            $ConsumeHistoryInfo412 = D('ConsumeHistory')->where("customer_id = '$customer_id' and type = 4 and status = 12")->order("add_time desc")->find();
                            $CustomerInfo_ = D('Customer')->field("pay_pass")->where("id = '$customer_id'")->find();
                            $CustomerInfo['pay_pass'] = $CustomerInfo_['pay_pass'];

                           //  //提现（德哥接口）
                           // var_dump("11111111111111",$res);die;
                        }
                        // var_dump($CustomerInfo);die;
                        $model = 'WithdrawalsOrder/withdrawalsOrder';
                        $xml_data = [
                            'customer_id' => $customer_id,
                            'amount' => $ConsumeHistoryInfo412['amount'],
                            'pay_pass' => $CustomerInfo['pay_pass'],
                            'pay_pass_unmatched' => '1',//密码校验略过
                            'location' => '40.002105,116.488438',
                            'province' => '北京市',
                            'city' => '北京市',
                            'country' => '朝阳区',
                            'address' => '中国北京市朝阳区阜通西大街',
                            'black_box' => 'eyJvcyI6IkFuZHJvaWQiLCJ2ZXJzaW9uIjoiMi4xLjMiLCJzZXNzaW9uX2lkIjoiOW1haWJlaTk1Zjc4YzhlNWRjNTA1ZjljOGIxM2E4YzFkNzE2MWQ5IiwiZGV2aWNlX2lkIjoiTW1SZlk4SWg4U1phMmpBdExtZGhMQ2dvSXlcL0UybitxMk94dEc5d2RHT3NkVTdcL09VN3RWVUIrNUZMY0h3ZldBWVM0PSIsImJ1bmRsZSI6ImNvbS56aGFvcWlhbmh1YS5jYXNoXzExNCIsImRhdGUiOiIxNTAyOTYyNjU5OTQzIiwiZGF0YSI6IlhiOHB0dDRCQklIbmhnNDZ0SGV5dFo4QUFEeT0ifQ==',
                            'push_id' => $CustomerInfo['push_id'],
                            'repay_id' => $ConsumeHistoryInfo412['repay_id']
                        ];
                        // var_dump($xml_data);die;
                        log::rong_write('**********重新请求银生宝执行放款流程|调用接口|'. $model .'|xml_data|'. json_encode($xml_data) .'|**********');
                        $test=D('Ajax')->ajaxPost($model, $xml_data);
                        $tes=json_decode($test,true);
                        $ret = Constant::getReturn(Constant::SUCCESS);
                        $ret['data']=$tes;
                    } else {
                        BusinessException::throwException("提现失败记录删除失败");
                    }

               // } else {
                //    BusinessException::throwException("提交consume_id与数据库中customer_pay_log数据不符");
                //}

            } else {
                BusinessException::throwException("提交consume_id与数据库中最新数据不符");
            }

        } catch (BusinessException $e) {
            log::rong_write('*********|异常抛出|code'. $e->getCode() .'|msg'. $e->getMessage() .'|**********');
            $ret = ['code'=>$e->getCode(), 'msg'=>$e->getMessage()];
        }
        log::rong_write('**********|ret|'. json_encode($ret) .'|*********');
        log::rong_write('***************************|orderReset_End|****************************');
        $this->ajaxReturn($ret);
    }
    // /**
    //  * [orderReset 解决提现失败接口]
    //  * @return [json] [code,msg]
    //  */
    // public function orderReset()
    // {
    //     log::rong_write('***************************|orderReset_Start|****************************');
    //     $customer_id = I("post.customer_id");
    //     $customer_id ? : BusinessException::throwException(Constant::INVALID_PARAMETER);
    //     // var_dump($customer_id);
    //     $consume_id = I("post.consume_id");
    //     $consume_id ? : BusinessException::throwException(Constant::INVALID_PARAMETER);
    //     log::rong_write('*********|接收数据|customer_id'. $customer_id .'|consume_id'. $consume_id .'|**********');

    //     try {
    //         $CustomerInfo = D('Customer')->has($customer_id);//customer_id数据库校验

    //         $ConsumeHistoryInfo = M('ConsumeHistory')->field("id")->where("customer_id = '$customer_id' and type = 5 and status <> 3")->order("add_time desc")->find();//
    //         $consume_id_ = $ConsumeHistoryInfo['id'];
    //         // var_dump($consume_id,$consume_id_);die;

    //         if ($consume_id == $consume_id_) {
    //         //这里先验证一下post上来的订单是不是跟ConsumeHistory表里最新的type=5的订单号相同。
    //         //若相同则进行下一步pay_log表验证数据是否相同
    //             $CustomerPayLogInfo = M('customer_pay_log')->field("consume_id, pay_time, ret_msg")->where("customer_id = '$customer_id'")->order("create_time desc")->find();
    //             $consume_id_ = $CustomerPayLogInfo['consume_id'];
    //             $pay_time = $CustomerPayLogInfo['pay_time'];
    //             $ret_msg = $CustomerPayLogInfo['ret_msg'];

    //             if ($consume_id == $consume_id_ && $pay_time == 0 && $ret_msg !== 'success') {

    //                 if ($CustomerInfo['cash_amount'] > $CustomerInfo['balance_cash_amount']) {
    //                     $res = M('Customer')->where("id = '$customer_id'")->setField(array(
    //                         'balance_cash_amount'   =>  $CustomerInfo['cash_amount'],
    //                         'balance_prepaid'       =>  '0'
    //                         ));
    //                     log::rong_write('**********|cash_amount>balance_cash_amount|res_Customer_setField|'. $res .'|**********');
    //                 } else {
    //                     $res = M('Customer')->where("id = '$customer_id'")->setField(array(
    //                         'balance_prepaid'       =>  '0'
    //                         ));
    //                     //这里提现失败的话逻辑上应该就是0，确保无误所以这里再设置一下
    //                     log::rong_write('**********|cash_amount<=balance_cash_amount|res_Customer_setField|'. $res .'|**********');
    //                 }

    //                 $res = M('ConsumeHistory')->where("id = '$consume_id' and type = 5 and status <> 3")->delete();
    //                 log::rong_write('**********|res_ConsumeHistory_delete|'. $res .'|**********');


    //                 if (isset($res) && !empty($res)) {
    //                     $ret = Constant::getReturn(Constant::SUCCESS);
    //                     // {
    //                     //     $consume_id_412 = D('ConsumeHistory')->field("consume_id")->where("customer_id = '$customer_id' and type = 4 and status = 12")->order("add_time desc")->find();
                            
    //                     //     $consume_id_412 = $consume_id_412['consume_id'];
    //                     //     $res = D('Finish')->WithdrawalOrderFinish($consume_id_412);
    //                     //     log::rong_write('**********|重新请求银生宝|res|Finish_WithdrawalOrderFinish|'. json_encode($res) .'|**********');
    //                     //    //  //提现（德哥接口）
    //                     //    var_dump("11111111111111",$res);die;
    //                     // }
                        
    //                     // $res ? $ret = Constant::getReturn(Constant::SUCCESS) : BusinessException::throwException("重新请求银生宝失败");
    //                 } else {
    //                     BusinessException::throwException("提现失败记录删除失败");
    //                 }

    //             } else {
    //                 BusinessException::throwException("提交consume_id与数据库中customer_pay_log数据不符");
    //             }

    //         } else {
    //             BusinessException::throwException("提交consume_id与数据库中最新数据不符");
    //         }

    //     } catch (BusinessException $e) {
    //         log::rong_write('*********|异常抛出|code'. $e->getCode() .'|msg'. $e->getMessage() .'|**********');
    //         $ret = ['code'=>$e->getCode(), 'msg'=>$e->getMessage()];
    //     }
    //     log::rong_write('**********|ret|'. json_encode($ret) .'|*********');
    //     log::rong_write('***************************|orderReset_End|****************************');
    //     $this->ajaxReturn($ret);
    // }
    
}
